package com.github.drinkjava2.gosqlgo;

import com.github.drinkjava2.gosqlgo.util.GsgStrUtils;
import com.github.drinkjava2.gosqlgo.util.TxtUtils;

// GSG imports

@SuppressWarnings("all")
public class QrySrcBuilder extends SrcBuilder {
	static final ServletTemplate template = GoSqlGoEnv.instance.getQryTemplate();
	static final Class<?> templateClass = template.getClass();

	public static QrySrcBuilder instance = new QrySrcBuilder();

	@Override
	public ServletTemplate getTemplate() {
		return template;
	}

	@Override
	public String createSourceCode(String className, String frontText) {
		SqlJavaPiece piece = SqlJavaPiece.parseFromFrontText(frontText);
		return createSourceCode(className, piece);
	}

	@Override
	public String createSourceCode(String className, SqlJavaPiece piece) {
		String classSrc = TxtUtils.getJavaSourceCodeUTF8(templateClass);
		classSrc = GsgStrUtils.replaceFirst(classSrc, "package " + templateClass.getPackage().getName(),
				"package " + GoSqlGoEnv.instance.getDeploy());
		String classDeclar = GsgStrUtils.substringBetween(classSrc, "public ", "{");
		classSrc = GsgStrUtils.replaceFirst(classSrc, classDeclar,
				"class " + className + " extends " + templateClass.getName());
		classSrc = GsgStrUtils.replaceFirst(classSrc, "// GSG IMPORTS", piece.getImports());
		classSrc = GsgStrUtils.replaceFirst(classSrc, "// GSG TAGS", buildGsgTagsForJavaSourceCode(piece));

		String sql = piece.getBody();
		sql = GsgStrUtils.replace(sql, "\\`", "`");
		sql = GsgStrUtils.replace(sql, "\"", "\\\"");
		String body = GsgStrUtils.substringBetween(classSrc, "/* GSG SQL BEGIN */", "/* GSG SQL END */");
		classSrc = GsgStrUtils.replaceFirst(classSrc, body,
				"\n" + "		String sql = \"" + sql + "\";" + "\n		");
		return classSrc;
	}

	@Override
	public String createFrontText(SqlJavaPiece piece) {
		String sql = piece.getBody();
		sql = GsgStrUtils.substringAfter(sql, "\"");
		sql = GsgStrUtils.substringBeforeLast(sql, "\"");
		sql = GsgStrUtils.replace(sql, "`", "\\`").trim();
		return buildFrontLeadingTagsAndImports(piece) + sql;
	}

}
